// 通知content-script
const sendMessageToContentScript = (message, callback) => {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
      if (callback) callback(response);
    });
  });
};

// 搜索
const handleSearch = (text) => {
  chrome.tabs.create({ url: 'https://www.baidu.com/s?ie=utf-8&wd=' + encodeURIComponent(text) });
};

// 翻译
const handleTranslate = async (text) => {
  // const url = 'http://127.0.0.1:612/translate';
  const url = 'http://45.40.202.60:612/translate';
  const res = await fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ words: text }),
  }).then((res) => res.json());
  if (res.code === 0) {
    const data = res.data.map((i) => i.dst).join(',');
    sendMessageToContentScript({ data }, (res) => {
      console.log(res);
    });
  } else {
    sendMessageToContentScript({ data: res.msg });
  }
};

// 接收消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  const { command, text } = request;
  switch (command) {
    case 'search':
      handleSearch(text);
      break;
    case 'translate':
      handleTranslate(text);
      break;
  }
  console.log(request);
  sendResponse('ok');
});

chrome.contextMenus.create({
  title: '使用百度搜索: %s',
  contexts: ['selection'],
  onclick(params) {
    handleSearch(params.selectionText);
  },
});

chrome.contextMenus.create({
  title: '翻译: %s',
  contexts: ['selection'],
  async onclick(params) {
    handleTranslate(params.selectionText);
  },
});
